# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     excelObj
   Description : excel 对象类
   Author :       pc
   date：          2018/1/7
-------------------------------------------------
   Change Activity:
                   2018/1/7:
-------------------------------------------------
"""
__author__ = 'pc'

import xlrd
import xlwt
import time


class ExcelObj:

    def start_cal(self):
        print("start cal ...")


class MonDetailExcel(ExcelObj):

    def __init__(self):
        self.excelType = "monDetail"

        # 待生成的excel

        # 读取日明细忽略标题及列名
        self.startRow = 2
        # 写入月明细的员工序号
        self.writeStaffNum = 1
        # 写入月明细的时标题行数
        self.writeHeadNum = 1
        # 处理的日期
        self.xlDay = 1

        # excel列表名称
        self._excelName = ""
        # 员工在月明细excel表中所在行的位置字典
        self._staffRow = {}
        # 需要写入月明细表的员工数据，格式[月明细中的行位置,员工姓名,工资,伙补]
        self._staffData = []

        # 员工1在日明细表中列的位置，常量，位置从0开始
        self._staffCol01 = 1
        # 员工1的工资在日明细表中列的位置，常量，位置从0开始
        self._staffSalaryCol01 = 6
        # 员工1的伙补在日明细表中列的位置，常量，位置从0开始
        self._staffSubsidyCol01 = 7

        # 员工2在日明细表中列的位置，常量，位置从0开始
        self._staffCol02 = 9
        # 员工2的工资在日明细表中列的位置，常量，位置从0开始
        self._staffSalaryCol02 = 14
        # 员工2的伙补在日明细表中列的位置，常量，位置从0开始
        self._staffSubsidyCol02 = 15

    def start_cal(self, nameTitle, fileList, exePath, calMonth):
        self._excelName = self.gen_excle_name(nameTitle, calMonth)
        print("开始汇总“" + nameTitle + "”月明细，并写入《" + self._excelName + "》。")

        # 初始化开始写入的行号
        self.writeStaffNum = 1
        # 初始化要写入的excel
        mdxl = xlwt.Workbook(encoding='utf-8')
        mdxlSheet = mdxl.add_sheet('mySheet', cell_overwrite_ok=True)

        for name in fileList:
            if (name.split("_")[0] == nameTitle and str(calMonth) + "月" in name.split("_")[2]):
                print("处理《" + name + "》中...")

                self.xlDay = self.cal_day(name)

                if (self.xlDay == -1):
                    print("处理《" + name + "》文件时，无法获取文件所归属的日期，跳过处理该文件")
                    continue

                self.write_head(mdxlSheet)
                self.readxl(exePath + "\\" + name, mdxlSheet)

        self.save(exePath, mdxl)

    # 计算需要生成的xls文件的文件名
    def gen_excle_name(self, nameTitle, calMonth):
        timeStamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        return nameTitle + "_月明细_" + str(calMonth) + "月份" + timeStamp + ".xls"

    # 计算当前处理日明细文件的日期
    def cal_day(self, fileName):
        startNum = fileName.split("_")[2].find("月")
        endNum = fileName.split("_")[2].find("日")

        if (startNum == -1 or endNum == -1):
            return -1

        startNum = startNum + 1
        endNum = endNum
        dayInfo = int(fileName.split("_")[2][startNum:endNum])
        return dayInfo

    # 写入文件头
    def write_head(mdxlSheet):
        """
        name SimSun,  宋体
        colour_index red, 字体颜色红色
        bold on, 加粗
        height 0x00F0; 字体大小 0x00F0 = 240 = 20*12 字体大小在excel 对应12

        wrap on, 自动换行开
        vert center,居中，还有顶端对齐 top ，底端对齐 bottom
        horiz center; 居中，还有左对齐 left，右对齐 right

        borders 边框
        """
        style = xlwt.easyxf("""
                font:
                    name SimSun,
                    colour_index red,
                    bold on,
                    height 0x00F0;
                align:
                    wrap on,
                    vert center,
                    horiz center;
                """)

        mdxlSheet.write(0, 0, "姓名", style)

        for i in range(1, 32):
            mdxlSheet.write(0, i + 1, i, style)

    # 逐行读取日明细并写入月明细
    def readxl(self, xlFile, mdxlSheet):
        """
        :param xlFile:
        :return:
        格式：
        """
        wb = xlrd.open_workbook(xlFile)
        ws = wb.sheets()[0]

        for rownum in range(self.startRow, ws.nrows):
            row = ws.row_values(rownum)
            if (row):
                # 计算员工1
                self.calStaffData(row, self._staffCol01, self._staffSalaryCol01, self._staffSubsidyCol01)
                self.write_xl(self._staffData, mdxlSheet)
                self._staffData = []

                # 计算员工2
                self.calStaffData(row, self._staffCol02, self._staffSalaryCol02, self._staffSubsidyCol02)
                self.write_xl(self._staffData, mdxlSheet)
                self._staffData = []

    # 计算员工数据
    def calStaffData(self, rowInfo=[], nameCol=0, salaryCol=0, subsidyCol=0):
        # 员工姓名不为空
        if (rowInfo[nameCol]):
            # 判断在月明细表的行号
            self.cal_row(rowInfo[nameCol])
            # 赋值员工姓名
            self._staffData.append(rowInfo[nameCol])
            # 取员工1工资
            self._staffData.append(rowInfo[salaryCol])
            # 取员工1伙补
            self._staffData.append(rowInfo[subsidyCol])
            # print(self._staffData)

    # 计算员工需要写入月明细的序号
    def cal_row(self, staffName):
        if (staffName in self._staffRow):
            self._staffData.append(self._staffRow[staffName])
        else:
            self._staffRow[staffName] = self.writeStaffNum
            self._staffData.append(self.writeStaffNum)
            self.writeStaffNum = self.writeStaffNum + 1

    def write_staff_name(self):
        print("")

    def write_xl(self, insertData, mdxlSheet):
        # 写入姓名
        staffNo = insertData[0]
        staffName = insertData[1]
        writeRow = (staffNo - 1) * 2 + 1
        styleName = xlwt.easyxf("""
                font:
                    name SimSun,
                    colour_index blue,
                    bold on,
                    height 0x00F0;
                align:
                    wrap on,
                    vert center,
                    horiz center;
                """)
        styleTitle = xlwt.easyxf("""
                font:
                    name SimSun,
                    colour_index black,
                    bold on,
                    height 0x00F0;
                align:
                    wrap on,
                    vert center,
                    horiz center;
                """)
        styleValue = xlwt.easyxf("""
                font:
                    name SimSun,
                    colour_index black,
                    height 0x00F0;
                align:
                    wrap on,
                    vert center,
                    horiz center;
                """)

        mdxlSheet.write_merge(writeRow, writeRow + 1, 0, 0, staffName, styleName)
        mdxlSheet.write(writeRow, 1, "工资", styleTitle)
        mdxlSheet.write(writeRow + 1, 1, "补贴", styleTitle)

        # 写入工资
        mdxlSheet.write(writeRow, self.xlDay + 1, insertData[2], styleValue)
        # 写入伙补
        mdxlSheet.write(writeRow + 1, self.xlDay + 1, insertData[3], styleValue)

    def save(self, exePath, mdxl):
        mdxl.save(exePath + "\\" + self._excelName)


class MonSumExcel(ExcelObj):
    def __init__(self):
        self.excelType = "monSum"

    def start_cal(self):
        print("start cal monSumExcel")


class DayDetailExcel(ExcelObj):
    def __init__(self):
        self.excelType = "dayDetail"
